package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Hes
 * @description 课程基本信息管理业务接口实现
 * @date: 2023/6/20 19:13
 */
@Service
@Slf4j
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;


    /**
     * 查询教学计划和子节点
     *
     * @param courseId
     * @return
     */
    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        List<TeachplanDto> teachplanTree = teachplanMapper.findTeachplanTree(courseId);
        System.out.println(teachplanTree);
        return teachplanTree;
    }

    /**
     * 添加和修改教学计划
     *
     * @param saveTeachplanDto
     */
    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {

        Long id = saveTeachplanDto.getId();
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (id != null && teachplan != null) {
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        }
        teachplan = new Teachplan();
        //获取同一门课的最大序号，用于排序
        int orderBy = getTeachplanCount(saveTeachplanDto.getCourseId(), saveTeachplanDto.getParentid());
        BeanUtils.copyProperties(saveTeachplanDto, teachplan);
        teachplan.setStatus(1);
        teachplan.setCreateDate(LocalDateTime.now());
        teachplan.setOrderby(orderBy + 1);
        teachplanMapper.insert(teachplan);

    }

    /**
     * 删除教学计划
     *
     * @param id
     * @param
     */
    @Transactional
    @Override
    public void delTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            XueChengPlusException.cast("没有此教学计划");
        }
        //有小章节不能删除
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, id);
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        if (teachplans.size() > 0) {
            XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
        }
        teachplanMapper.deleteById(id);
        //删除TeachplanMedia
        teachplans.forEach(item -> {
            Long itemId = item.getId();
            LambdaQueryWrapper<TeachplanMedia> mediaLambdaQueryWrapper = new LambdaQueryWrapper<>();
            mediaLambdaQueryWrapper.eq(TeachplanMedia::getTeachplanId, itemId);
            Integer integer = teachplanMediaMapper.selectCount(mediaLambdaQueryWrapper);
            if (integer > 0) {
                teachplanMediaMapper.delete(mediaLambdaQueryWrapper);
            }
        });
    }

    /**
     * 课程计划列表下移
     *
     * @param teachplanId
     */
    @Override
    @Transactional
    public void moveDown(Long teachplanId) {
        //查同级元素个数
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());
        Integer integer = teachplanMapper.selectCount(queryWrapper);
        //是否是最后一个
        if (teachplan.getOrderby() == integer) {
            XueChengPlusException.cast("当前已在最后，不能下移");
        }
        //不是，把前一个下一个位置上移，自己下移
        queryWrapper.eq(Teachplan::getOrderby, teachplan.getOrderby() + 1);
        Teachplan teachplanup = teachplanMapper.selectOne(queryWrapper);
        teachplanup.setOrderby(teachplan.getOrderby());
        teachplanMapper.updateById(teachplanup);
        Integer orderby = teachplan.getOrderby();
        teachplan.setOrderby(orderby + 1);
        teachplanMapper.updateById(teachplan);
    }

    /**
     * 课程计划列表下移
     *
     * @param teachplanId
     */
    @Override
    @Transactional
    public void moveUp(Long teachplanId) {
        //查同级元素个数
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, teachplan.getParentid());

        //是否是最后一个
        if (teachplan.getOrderby() == 1) {
            XueChengPlusException.cast("当前已在第一位，不能上移");
        }
        //不是，把前一个上一个位置下移，自己上移
        queryWrapper.eq(Teachplan::getOrderby, teachplan.getOrderby() - 1);
        Teachplan teachplanup = teachplanMapper.selectOne(queryWrapper);
        teachplanup.setOrderby(teachplan.getOrderby());
        teachplanMapper.updateById(teachplanup);
        Integer orderby = teachplan.getOrderby();
        teachplan.setOrderby(orderby - 1);
        teachplanMapper.updateById(teachplan);
    }

    /**
     * @param teachplanMediaDto
     */
    @Override
    @Transactional
    public TeachplanMedia associationMedia(BindTeachplanMediaDto teachplanMediaDto) {
        String mediaId = teachplanMediaDto.getMediaId();
        Long teachplanId = teachplanMediaDto.getTeachplanId();
        String fileName = teachplanMediaDto.getFileName();

        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null) {
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade != 2) {
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId, teachplanId));
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        Long courseId = teachplan.getCourseId();
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(fileName);
        teachplanMedia.setMediaId(mediaId);
        teachplanMedia.setCourseId(courseId);
        int insert = teachplanMediaMapper.insert(teachplanMedia);
        if (insert <= 0) {
            XueChengPlusException.cast("添加教学媒资失败");
        }
        return teachplanMedia;

    }

    @Override
    @Transactional
    public void delAssociation(String mediaId, Long teachPlanId) {
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        if (teachplan == null) {
            XueChengPlusException.cast("没找到这门课的教学计划");
        }
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, teachPlanId)
                .eq(TeachplanMedia::getMediaId, mediaId);
        Integer integer = teachplanMediaMapper.selectCount(queryWrapper);
        if (integer <= 0) {
            XueChengPlusException.cast("课程计划，没有绑定媒资文件");
        }
        teachplanMediaMapper.delete(queryWrapper);

    }

    /**
     * 获取同一门课序号
     *
     * @param courseId
     * @param parentId
     * @return
     */
    public int getTeachplanCount(Long courseId, Long parentId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId)
                .eq(Teachplan::getParentid, parentId);
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        return teachplans.size();

    }
}
